<template>
  <div class="equipment-maintenance-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备维保管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleCreatePlan"
              >新建维保计划</el-button
            >
            <el-button type="success" @click="handleCreateTask"
              >创建维保工单</el-button
            >
            <el-button type="warning" @click="handleRepairReport"
              >报修登记</el-button
            >
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="工单编号">
          <el-input v-model="queryForm.orderNo" placeholder="请输入工单编号" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="queryForm.equipmentName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="维保类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择维保类型"
            clearable
          >
            <el-option
              v-for="item in maintenanceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维保日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 维保工单列表 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="orderNo" label="工单编号" width="130" />
        <el-table-column prop="equipmentCode" label="设备编码" width="120" />
        <el-table-column prop="equipmentName" label="设备名称" width="150" />
        <el-table-column prop="type" label="维保类型" width="120">
          <template #default="scope">
            <el-tag :type="getMaintenanceTypeTag(scope.row.type)">
              {{ getMaintenanceTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planDate" label="计划日期" width="120" />
        <el-table-column prop="actualDate" label="实际日期" width="120" />
        <el-table-column prop="maintainer" label="维保人员" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cost" label="维保费用" width="120">
          <template #default="scope">
            {{ scope.row.cost ? `¥${scope.row.cost}` : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleExecute(scope.row)"
              v-if="scope.row.status === 'pending'"
              >执行</el-button
            >
            <el-button link type="primary" @click="handleViewDetail(scope.row)"
              >详情</el-button
            >
            <el-button link type="primary" @click="handleViewParts(scope.row)"
              >备件</el-button
            >
            <el-button
              link
              type="danger"
              @click="handleCancel(scope.row)"
              v-if="scope.row.status === 'pending'"
              >取消</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 维保计划对话框 -->
    <el-dialog v-model="planDialogVisible" title="维保计划" width="60%">
      <el-form
        ref="planFormRef"
        :model="planForm"
        :rules="planRules"
        label-width="100px"
      >
        <el-form-item label="计划名称" prop="name">
          <el-input v-model="planForm.name" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="维保类型" prop="type">
          <el-select v-model="planForm.type" placeholder="请选择维保类型">
            <el-option
              v-for="item in maintenanceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维保周期" prop="cycle">
          <el-select v-model="planForm.cycle" placeholder="请选择维保周期">
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
            <el-option label="每季度" value="quarterly" />
            <el-option label="每年" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备清单" prop="equipments">
          <el-select
            v-model="planForm.equipments"
            multiple
            placeholder="请选择设备"
          >
            <el-option
              v-for="item in equipmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维保内容">
          <el-button type="primary" @click="handleAddItem">添加项目</el-button>
          <el-table :data="planForm.items" border style="margin-top: 10px">
            <el-table-column prop="name" label="项目名称">
              <template #default="scope">
                <el-input
                  v-model="scope.row.name"
                  placeholder="请输入项目名称"
                />
              </template>
            </el-table-column>
            <el-table-column prop="standard" label="维保标准">
              <template #default="scope">
                <el-input
                  v-model="scope.row.standard"
                  placeholder="请输入维保标准"
                />
              </template>
            </el-table-column>
            <el-table-column prop="parts" label="所需备件">
              <template #default="scope">
                <el-input
                  v-model="scope.row.parts"
                  placeholder="请输入所需备件"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleRemoveItem(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="planDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePlanSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维保执行对话框 -->
    <el-dialog v-model="executeDialogVisible" title="维保执行" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编号">{{
          currentTask.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="设备编码">{{
          currentTask.equipmentCode
        }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{
          currentTask.equipmentName
        }}</el-descriptions-item>
        <el-descriptions-item label="维保类型">{{
          getMaintenanceTypeText(currentTask.type)
        }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="maintenanceItems" border style="margin-top: 20px">
        <el-table-column prop="name" label="维保项目" />
        <el-table-column prop="standard" label="维保标准" />
        <el-table-column prop="parts" label="所需备件" />
        <el-table-column label="执行结果" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.result" placeholder="请选择">
              <el-option label="正常" value="normal" />
              <el-option label="异常" value="abnormal" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
      </el-table>

      <el-form :model="executeForm" style="margin-top: 20px">
        <el-form-item label="备件消耗">
          <el-button type="primary" @click="handleAddPart">添加备件</el-button>
          <el-table :data="executeForm.parts" border style="margin-top: 10px">
            <el-table-column prop="code" label="备件编码" width="150">
              <template #default="scope">
                <el-select v-model="scope.row.code" placeholder="请选择备件">
                  <el-option
                    v-for="item in partsOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="备件名称" width="150" />
            <el-table-column prop="quantity" label="数量" width="120">
              <template #default="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="120" />
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="scope">
                {{ calculateAmount(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="handleRemovePart(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="维保结果">
          <el-radio-group v-model="executeForm.result">
            <el-radio label="completed">完成</el-radio>
            <el-radio label="incomplete">未完成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="维保总结">
          <el-input
            v-model="executeForm.summary"
            type="textarea"
            rows="3"
            placeholder="请输入维保总结"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="executeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExecuteSubmit"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 备件消耗对话框 -->
    <el-dialog v-model="partsDialogVisible" title="备件消耗记录" width="60%">
      <el-table :data="partsRecords" border>
        <el-table-column prop="code" label="备件编码" />
        <el-table-column prop="name" label="备件名称" />
        <el-table-column prop="specification" label="规格型号" />
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="price" label="单价">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额">
          <template #default="scope"> ¥{{ scope.row.amount }} </template>
        </el-table-column>
        <el-table-column prop="useDate" label="使用日期" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 查询表单
const queryForm = reactive({
  orderNo: "",
  equipmentName: "",
  type: "",
  status: "",
  dateRange: [],
});

// 维保类型选项
const maintenanceTypes = [
  { value: "routine", label: "日常保养" },
  { value: "periodic", label: "定期维护" },
  { value: "repair", label: "故障维修" },
  { value: "overhaul", label: "大修" },
  { value: "improvement", label: "改造升级" },
];

// 状态选项
const statusOptions = [
  { value: "pending", label: "待执行" },
  { value: "processing", label: "执行中" },
  { value: "completed", label: "已完成" },
  { value: "cancelled", label: "已取消" },
  { value: "suspended", label: "已暂停" },
];

// 设备选项
const equipmentOptions = [
  { value: "EQ001", label: "数控车床-EQ001" },
  { value: "EQ002", label: "加工中心-EQ002" },
  { value: "EQ003", label: "三坐标测量仪-EQ003" },
  { value: "EQ004", label: "空气压缩机-EQ004" },
  { value: "EQ005", label: "工业机器人-EQ005" },
];

// 备件选项
const partsOptions = [
  { value: "P001", label: "轴承-6205-2RS" },
  { value: "P002", label: "油封-TC20×35×7" },
  { value: "P003", label: "同步带-5M-400" },
  { value: "P004", label: "电机-Y90L-4" },
  { value: "P005", label: "传感器-E3Z-T61" },
];

// 表格数据
const tableData = ref([
  {
    orderNo: "M202403001",
    equipmentCode: "EQ001",
    equipmentName: "数控车床",
    type: "routine",
    planDate: "2024-03-20",
    actualDate: "",
    maintainer: "张三",
    status: "pending",
    cost: null,
  },
  {
    orderNo: "M202403002",
    equipmentCode: "EQ002",
    equipmentName: "加工中心",
    type: "periodic",
    planDate: "2024-03-19",
    actualDate: "2024-03-19",
    maintainer: "李四",
    status: "completed",
    cost: 1500.0,
  },
  {
    orderNo: "M202403003",
    equipmentCode: "EQ003",
    equipmentName: "三坐标测量仪",
    type: "repair",
    planDate: "2024-03-18",
    actualDate: "2024-03-18",
    maintainer: "王五",
    status: "completed",
    cost: 3200.0,
  },
  {
    orderNo: "M202403004",
    equipmentCode: "EQ004",
    equipmentName: "空气压缩机",
    type: "routine",
    planDate: "2024-03-20",
    actualDate: "",
    maintainer: "赵六",
    status: "processing",
    cost: null,
  },
  {
    orderNo: "M202403005",
    equipmentCode: "EQ005",
    equipmentName: "工业机器人",
    type: "overhaul",
    planDate: "2024-03-25",
    actualDate: "",
    maintainer: "张三",
    status: "pending",
    cost: null,
  },
]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 维保计划对话框
const planDialogVisible = ref(false);
const planFormRef = ref(null);
const planForm = reactive({
  name: "",
  type: "",
  cycle: "",
  equipments: [],
  items: [],
});

// 维保执行对话框
const executeDialogVisible = ref(false);
const currentTask = ref({});
const maintenanceItems = ref([
  {
    name: "设备清洁",
    standard: "设备表面及周边环境清洁，无油污、灰尘",
    parts: "清洁工具",
    result: "",
    remark: "",
  },
  {
    name: "润滑检查",
    standard: "各润滑点油量充足，油质正常，无漏油",
    parts: "润滑油、黄油",
    result: "",
    remark: "",
  },
  {
    name: "紧固件检查",
    standard: "所有紧固件无松动，紧固到位",
    parts: "扳手套装",
    result: "",
    remark: "",
  },
  {
    name: "传动系统检查",
    standard: "传动部件运转平稳，无异响、无振动",
    parts: "测振仪",
    result: "",
    remark: "",
  },
  {
    name: "电气系统检查",
    standard: "线路完好，接点牢固，绝缘良好",
    parts: "万用表",
    result: "",
    remark: "",
  },
  {
    name: "安全装置检查",
    standard: "各类保护装置工作正常，警示标识完整",
    parts: "检测工具",
    result: "",
    remark: "",
  },
]);

// 备件消耗记录
const partsDialogVisible = ref(false);
const partsRecords = ref([
  {
    code: "P001",
    name: "轴承",
    specification: "6205-2RS",
    quantity: 2,
    price: 150.0,
    amount: 300.0,
    useDate: "2024-03-19",
  },
  {
    code: "P002",
    name: "油封",
    specification: "TC20×35×7",
    quantity: 4,
    price: 25.0,
    amount: 100.0,
    useDate: "2024-03-19",
  },
  {
    code: "P003",
    name: "同步带",
    specification: "5M-400",
    quantity: 1,
    price: 180.0,
    amount: 180.0,
    useDate: "2024-03-18",
  },
  {
    code: "P004",
    name: "传感器",
    specification: "E3Z-T61",
    quantity: 2,
    price: 320.0,
    amount: 640.0,
    useDate: "2024-03-18",
  },
]);

// 执行表单
const executeForm = reactive({
  result: "",
  summary: "",
  parts: [],
});

// 表单校验规则
const planRules = {
  name: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择维保类型", trigger: "change" }],
  cycle: [{ required: true, message: "请选择维保周期", trigger: "change" }],
  equipments: [{ required: true, message: "请选择设备", trigger: "change" }],
};

// 获取维保类型标签
const getMaintenanceTypeTag = (type) => {
  const typeMap = {
    routine: "",
    periodic: "success",
    repair: "warning",
    overhaul: "danger",
    improvement: "info",
  };
  return typeMap[type];
};

// 获取维保类型文本
const getMaintenanceTypeText = (type) => {
  const typeMap = {
    routine: "日常保养",
    periodic: "定期维护",
    repair: "故障维修",
    overhaul: "大修",
    improvement: "改造升级",
  };
  return typeMap[type];
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: "warning",
    processing: "primary",
    completed: "success",
    cancelled: "info",
    suspended: "danger",
  };
  return statusMap[status];
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: "待执行",
    processing: "执行中",
    completed: "已完成",
    cancelled: "已取消",
    suspended: "已暂停",
  };
  return statusMap[status];
};

// 计算金额
const calculateAmount = (row) => {
  if (row.quantity && row.price) {
    return `¥${(row.quantity * row.price).toFixed(2)}`;
  }
  return "-";
};

// 查询方法
const handleSearch = () => {
  ElMessage.success("查询成功");
};

const handleReset = () => {
  queryForm.orderNo = "";
  queryForm.equipmentName = "";
  queryForm.type = "";
  queryForm.status = "";
  queryForm.dateRange = [];
};

// 维保计划方法
const handleCreatePlan = () => {
  planDialogVisible.value = true;
  Object.assign(planForm, {
    name: "",
    type: "",
    cycle: "",
    equipments: [],
    items: [],
  });
};

const handleAddItem = () => {
  planForm.items.push({
    name: "",
    standard: "",
    parts: "",
  });
};

const handleRemoveItem = (index) => {
  planForm.items.splice(index, 1);
};

const handlePlanSubmit = async () => {
  if (!planFormRef.value) return;
  await planFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("创建成功");
      planDialogVisible.value = false;
    }
  });
};

// 维保执行方法
const handleExecute = (row) => {
  currentTask.value = row;
  executeDialogVisible.value = true;
  executeForm.result = "";
  executeForm.summary = "";
  executeForm.parts = [];
  maintenanceItems.value.forEach((item) => {
    item.result = "";
    item.remark = "";
  });
};

const handleAddPart = () => {
  executeForm.parts.push({
    code: "",
    name: "",
    quantity: 1,
    price: 0,
    amount: 0,
  });
};

const handleRemovePart = (index) => {
  executeForm.parts.splice(index, 1);
};

const handleExecuteSubmit = () => {
  if (!executeForm.result) {
    ElMessage.warning("请选择维保结果");
    return;
  }
  ElMessage.success("提交成功");
  executeDialogVisible.value = false;
};

// 其他方法
const handleCreateTask = () => {
  ElMessage.success("创建工单");
};

const handleRepairReport = () => {
  ElMessage.success("报修登记");
};

const handleViewDetail = (row) => {
  ElMessage.success("查看详情：" + row.orderNo);
};

const handleViewParts = (row) => {
  partsDialogVisible.value = true;
};

const handleCancel = (row) => {
  ElMessageBox.confirm("确认取消该维保工单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ElMessage.success("取消成功");
  });
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.equipment-maintenance-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>
